package com.study.common.utils;

import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 获取堆内堆外内存
 *
 * @author wuxj
 */
public class RamUtil {

    public static void getRam() {
        System.out.println("----------------------------------------------------------------------------------------");
        System.out.println(MessageFormat.format("堆内最大可分配内存：{0}", Runtime.getRuntime().maxMemory()));
        System.out.println(MessageFormat.format("堆内已分配内存：{0}", Runtime.getRuntime().totalMemory()));
        System.out.println(MessageFormat.format("堆内已分配内存未使用内存：{0}", Runtime.getRuntime().freeMemory()));

        //获取堆外内存大小
        try {
            //通过反射取得私有数据
            Class c = Class.forName("java.nio.Bits");
            //获取堆外内存总大小
            Field maxMemory = c.getDeclaredField("maxMemory");
            maxMemory.setAccessible(true);
            //获取堆外内存使用大小
            Field reservedMemory = c.getDeclaredField("reservedMemory");
            reservedMemory.setAccessible(true);
            synchronized (c) {
                Long maxMemoryValue = (Long) maxMemory.get(null);
                AtomicLong reservedMemoryValue = (AtomicLong) reservedMemory.get(null);
                System.out.println(MessageFormat.format("堆外内存总大小：{0}", maxMemoryValue));
                System.out.println(MessageFormat.format("堆外内存使用大小：{0}", reservedMemoryValue));
            }
            System.out.println("----------------------------------------------------------------------------------------");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
